import React, { useEffect, useState } from "react";
import request from "../../utils/request";
import { useNavigate } from "react-router-dom";
import { debounce } from "lodash";
import "./style.scss";
interface ProductState {
  title: string;
  id: string;
  children: ItemState[];
}

export interface ItemState {
  title: string;
  id: string;
  url: string;
  price: number;
  desc: string;
  sku: {
    colors: string[];
    size: string[];
  };
}

const Index = () => {
  const [product, setProduct] = useState<ProductState[]>([]);
  const [activeIndex, setActiveIndex] = useState(0);
  const navigate = useNavigate();
  const fetchProduct = async () => {
    const resp = await request.get("/api/product");
    setProduct(resp.data.data);
  };
  const changeActiveIndex = debounce((i: number) => {
    setActiveIndex(i);
  }, 1000);
  useEffect(() => {
    fetchProduct();
  }, []);
  if (product.length === 0) return <div>...</div>;

  return (
    <div className="product">
      <div className="title">
        {product.map((v, i) => {
          return (
            <span
              onClick={() => changeActiveIndex(i)}
              className={i === activeIndex ? "active" : ""}
              key={v.id}
            >
              {v.title}
            </span>
          );
        })}
      </div>
      <div className="content">
        {product[activeIndex].children.map((v) => {
          return (
            <dl key={v.id} onClick={() => navigate("/detail/" + v.id)}>
              <dt>
                <img src={v.url} alt="" />
              </dt>
              <dd>
                <h3>{v.title}</h3>
                <p>{v.desc}</p>
              </dd>
            </dl>
          );
        })}
      </div>
    </div>
  );
};

export default Index;
